/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import eu.bitwalker.useragentutils.UserAgent;
import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.generator.entity.SysLogininforEntity;
import io.renren.modules.generator.service.SysLogininforService;
import io.renren.modules.oss.utils.AddressUtils;
import io.renren.modules.oss.utils.IpUtils;
import io.renren.modules.oss.utils.ServletUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.SysCaptchaService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	@Autowired
	private SysLogininforService sysLogininforService;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		String loginMsg=null;
		String loginStatus=null;
		if(!captcha){
				loginMsg="验证码不正确";
		loginStatus="1";
			return R.error("验证码不正确");

		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			loginMsg="账号或密码不正确";
			loginStatus="1";
			saveLogininfo(form.getUsername(), loginMsg, loginStatus);
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			loginMsg="账号已被锁定";
			loginStatus="1";
			saveLogininfo(form.getUsername(), loginMsg, loginStatus);
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		//保存登陆日志
		saveLogininfo(form.getUsername(), null, null);
		return r;
	}

	private void saveLogininfo(String userName, String loginMsg, String loginStatus) {
		SysLogininforEntity sysLogininforEntity = new SysLogininforEntity();
		sysLogininforEntity.setUserName(userName);
		HttpServletRequest request = ServletUtils.getRequest();
		String remoteAddr = request.getRemoteAddr();
		String ipAddr = IpUtils.getIpAddr(request);
		sysLogininforEntity.setIpaddr(ipAddr);
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
		// 获取客户端操作系统
		String os = userAgent.getOperatingSystem().getName();
		// 获取客户端浏览器
		String browser = userAgent.getBrowser().getName();
		String realAddressByIP = AddressUtils.getRealAddressByIP(ipAddr);
		sysLogininforEntity.setLoginLocation(realAddressByIP);
		sysLogininforEntity.setBrowser(browser);
		sysLogininforEntity.setOs(os);
		sysLogininforEntity.setType(String.valueOf(0));
		sysLogininforEntity.setStatus(loginStatus ==null?"0": loginStatus);
		sysLogininforEntity.setMsg(loginMsg ==null?"登陆成功": loginMsg);
		sysLogininforEntity.setLoginTime(new Date());
		sysLogininforService.save(sysLogininforEntity);
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout() {
		sysUserTokenService.logout(getUserId());
		SysUserEntity userEntity = ShiroUtils.getUserEntity();
		//保存日志
		saveLogininfo(userEntity.getUsername(), "退出成功", null);
		return R.ok();
	}

}
